import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';
import 'package:xlsk/api/model/index.dart';
import 'package:xlsk/utils/storage.dart';

class UserInfo with ChangeNotifier{
  var userInfo = {};

  void saveUserInfo(data){
    this.userInfo = data;
    notifyListeners();
  }

  checkLogin(context) async{ // 检查是否登录,如果登录则返回true
    var provider_userinfo = Provider.of<UserInfo>(context,listen: false);
    // print('provider_userinfo.userInfo');print(provider_userinfo.userInfo);
    if(provider_userinfo.userInfo is! Object){return false;}
    if(provider_userinfo.userInfo.containsKey('token')){
      return true;
    }else{
      var userInfo = await Storage.getString('userInfo');
      if(userInfo != null && userInfo != 'null'){
        //内存中存在userInfo,则发送一个请求判断token是否失效
        var res = await IndexApi().getKecheng(context, '/kecheng');
        if(res['code'] == 200){
          return true;
        }else{
          return false;
        }
      }else{
        return false;
      }
    }
  }

  checkInfo(context) async{
    var provider_userinfo = Provider.of<UserInfo>(context,listen: false);
    // print('provider_userinfo.userInfo');print(provider_userinfo.userInfo);
    if(provider_userinfo.userInfo is! Object){return false;}
    if(provider_userinfo.userInfo.containsKey('token')){
      return true;
    }else{
      var userInfo = await Storage.getString('userInfo');
      if(userInfo != null && userInfo != 'null'){
        provider_userinfo.saveUserInfo(jsonDecode(userInfo));
        return true;
      }else{
        return false;
      }
    }
  }
}